package com.vchecker.iobd_checker;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.vchecker.iobd_checker.broadcast.BluetoothConnectReceiver;
import com.vchecker.iobd_checker.broadcast.BluetoothSearchReceiver;
import com.vchecker.iobd_checker.model.CommDefine;
import com.vchecker.iobd_checker.model.CommEvent;
import com.vchecker.iobd_checker.model.Device;
import com.vchecker.iobd_checker.utils.ClsUtils;
import com.vchecker.iobd_checker.utils.DlgUtils;
import com.vchecker.iobd_checker.utils.ShellUtils;
import com.vchecker.iobd_checker.utils.Upgrad;
import com.vchecker.iobd_checker.utils.VDialog;
import com.vchecker.iobd_checker.view.ProgressButton;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends ActionBarActivity {
    public static final String TAG = "MainActivity";
    public static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";

    BluetoothSearchReceiver searchReceiver = new BluetoothSearchReceiver();
    BluetoothConnectReceiver connectReceiver = new BluetoothConnectReceiver();

    public Context context;
    public StringBuilder strLog = new StringBuilder();

    public boolean isShowLog = false;
    public boolean isPauseLog = true;
    public String currVerKey = "";
    public static Upgrad.VerInfo currVerInfo = null;

    public static List<String> lstDevicesText = new ArrayList<String>();
    public List<BluetoothDevice> lstDevices = new ArrayList<BluetoothDevice>();
    public BluetoothAdapter btAdapt;
    public BluetoothSocket btSocket;
    public ArrayAdapter<String> adtDevicesText;
    public BluetoothHandler bh;
    public boolean isSearch = false;        //是否正在搜索设备
    public boolean isResearch = false;      //是否为重复搜索设备
    public boolean isAutoResearch = false;  //是否自动重新搜索设备
    public boolean isPair = false;          //是否正在配对设备
    public boolean isConnect = false;       //是否正在连接设备
    public int currPairIndex = 0;
    public int currConnectIndex = 0;
    public int currConnectIndexMax = 0;
    public int upgradSuccess = 0;
    public int upgradFailure = 0;
    public int upgradNoNew = 0;
    public int upgradLanErr = 0;
    public int upgradVerErr = 0;

    int iDelayIndex = 0;
    int iDelayCount = 120;

    public List<Device> lstHistoricalDevice = new ArrayList<Device>();

    @Bind(R.id.spinName)
    Spinner spinName;
    @Bind(R.id.spinLan)
    Spinner spinLan;
    @Bind(R.id.btnSearch)
    Button btnSearch;
    @Bind(R.id.btnClearPair)
    Button btnClearPair;
    @Bind(R.id.btnUpgrad)
    ProgressButton mbtnUpgrad;
    @Bind(R.id.tvLog)
    TextView tvLog;
    @Bind(R.id.svLog)
    ScrollView svLog;
    @Bind(R.id.lvDevices)
    ListView lvBTDevices;
    @Bind(R.id.tvCount)
    TextView tvCount;
    @Bind(R.id.tvSuccess)
    TextView tvSuccess;
    @Bind(R.id.tvFailure)
    TextView tvFailure;
    @Bind(R.id.tvVerErr)
    TextView tvVerErr;
    @Bind(R.id.tvLanErr)
    TextView tvLanErr;


    private Handler handler;

    //强制升级标志
    boolean mUpgardFlag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        context = this;
        this.setTitle(this.getTitle() + getVersionName(this));

        EventBus.getDefault().register(this);

        btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
        for (Object obj : btAdapt.getBondedDevices()) {
            BluetoothDevice bd = (BluetoothDevice) obj;
            unpair(bd);
        }
        btAdapt.disable();
        if (!btAdapt.isEnabled())
            btAdapt.enable();   //打开蓝牙


        // ListView及其数据源 适配器
        lstDevices.clear();
        lstDevicesText.clear();
        adtDevicesText = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, lstDevicesText);
        lvBTDevices.setAdapter(adtDevicesText);

        svLog.setVisibility(View.GONE);

        spinName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                int name = spinName.getSelectedItemPosition();
                int lan = spinLan.getSelectedItemPosition();
                updateCurrVerInfo(name, lan);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                int name = spinName.getSelectedItemPosition();
                int lan = spinLan.getSelectedItemPosition();
                updateCurrVerInfo(name, lan);
            }
        });
        spinLan.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                int name = spinName.getSelectedItemPosition();
                int lan = spinLan.getSelectedItemPosition();
                updateCurrVerInfo(name, lan);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                int name = spinName.getSelectedItemPosition();
                int lan = spinLan.getSelectedItemPosition();
                updateCurrVerInfo(name, lan);
            }
        });
        btnSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isConnect) {
                    Toast.makeText(MainActivity.this, "正在升级设备...", Toast.LENGTH_LONG).show();
                    return;
                }
                btnSearch.setText("正在搜索设备...");

                if (!btAdapt.isEnabled())
                    btAdapt.enable();   //打开蓝牙
                //
                isSearch = true;

                startActivityForResult(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS), 0);


            }
        });


        btnClearPair.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                if(isSearch){
//                    Toast.makeText(MainActivity.this,"正在搜索设备...",Toast.LENGTH_LONG).show();
//                    return;
//                }
//                if(isConnect){
//                    Toast.makeText(MainActivity.this,"正在升级设备...",Toast.LENGTH_LONG).show();
//                    return;
//                }
//
//                if (!btAdapt.isEnabled())
//                    btAdapt.enable();   //打开蓝牙
//                for (Object obj : btAdapt.getBondedDevices()) {
//                    BluetoothDevice bd = (BluetoothDevice) obj;
//                    unpair(bd);
//                }
//                // ListView及其数据源 适配器
//                DataSupport.deleteAll(Device.class);
//                lstHistoricalDevice.clear();
//
//                lstDevices.clear();
//                lstDevicesText.clear();
//                adtDevicesText.notifyDataSetChanged();
            }
        });
        mbtnUpgrad.setText("开始升级");
        mbtnUpgrad.setOnProgressButtonClickListener(new ProgressButton.OnProgressButtonClickListener() {
            @Override
            public void onClickListener() {
                // TODO Auto-generated method stub


                btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
                for (Object obj : btAdapt.getBondedDevices()) {
                    BluetoothDevice bd = (BluetoothDevice) obj;
                    unpair(bd);
                }
                btAdapt.disable();
                if (!btAdapt.isEnabled())
                    btAdapt.enable();   //打开蓝牙

                startUpgrad();
            }
        });

        lvBTDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (isSearch) return;

                if (lstDevices.get(position).getBondState() == BluetoothDevice.BOND_BONDED) {
//                    addLog("连接蓝牙:" + lstDevices.get(position).getAddress());
//                    currConnectIndex = position;
//                    bh= new BluetoothHandler(context,handler);
//                    bh.connect(lstDevices.get(position));
                } else {
//                    if (lstDevicesText.get(position).indexOf("未配对") >= 0) {
//                        addLog("配对蓝牙:" + lstDevices.get(position).getAddress());
//                        currPairIndex = position;
//                        isPair =true;
//                        pair(lstDevices.get(position).getAddress(), "1234");
//                    }
                }
            }
        });

//        // 注册Receiver来获取蓝牙设备相关的结果
//        IntentFilter intentSearch = new IntentFilter();
//        intentSearch.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
//        intentSearch.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
//        intentSearch.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
//        intentSearch.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
//        intentSearch.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
//
//        registerReceiver(searchReceiver, intentSearch);

//        IntentFilter intentPair = new IntentFilter();
//        intentPair.addAction("android.bluetooth.device.action.PAIRING_REQUEST");//自動匹配的广播
//        registerReceiver(connectReceiver, intentPair);

        SQLiteDatabase db = Connector.getDatabase();

        lstHistoricalDevice = DataSupport.findAll(Device.class);

        //更新硬件库文件
        new Upgrad(MainActivity.this).updateUpgradFile();

        handler = new Handler() {
            public void handleMessage(Message msg) {
                //根据message中的信息对主线程的UI进行改动
                handleMsg(msg);
            }
        };

        startUpgrad();

        handLog.postDelayed(runLog, 1000);
    }
    //获取版本号
    public static int getVersionCode(Context context){
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        }catch(PackageManager.NameNotFoundException e){
            return 0;
        }
    }//获取版本号
    public static String getVersionName(Context context){
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        }catch(PackageManager.NameNotFoundException e){
            return "";
        }
    }

    public void startUpgrad() {
        if (!btAdapt.isEnabled())
            btAdapt.enable();   //打开蓝牙

        final VDialog dlgConfig = DlgUtils.showConfig(MainActivity.this);
        dlgConfig.setOnDismissListener(new DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog) {
                // TODO Auto-generated method stub
                if (dlgConfig.getResult() == VDialog.RESULT_OK) {

                    int name = dlgConfig.getIntValue("Name", 1) - 1;
                    int lan = dlgConfig.getIntValue("Lan", 1) - 1;
                    if (dlgConfig.getIntValue("Upgrad", 1) == 1)
                        mUpgardFlag = true;
                    else
                        mUpgardFlag = false;

                    updateCurrVerInfo(name, lan);

                    final VDialog dlgConnect = DlgUtils.showConnect(MainActivity.this, false);
                    dlgConnect.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            // TODO Auto-generated method stub
                            if (dlgConnect.getResult() == VDialog.RESULT_CONFIG) {
                                Intent intent = new Intent(
                                        Settings.ACTION_BLUETOOTH_SETTINGS);
                                startActivityForResult(intent, 0);
                            } else {
                                exitApp();
                            }
                        }
                    });
                    dlgConnect.show();
                } else {
                    exitApp();
                }
            }
        });
        dlgConfig.show();


//        if(isSearch){
//            Toast.makeText(MainActivity.this,"正在搜索设备...",Toast.LENGTH_LONG).show();
//            return;
//        }
//        if(isConnect){
//            Toast.makeText(MainActivity.this,"正在升级设备...",Toast.LENGTH_LONG).show();
//            return;
//        }
//
//        spinName.setEnabled(false);
//        spinLan.setEnabled(false);
//        currConnectIndex = -1;
//        btnSearch.setEnabled(false);
//        btnClearPair.setEnabled(false);


//        isConnect = true;
//
//        upgradFailure = 0;
//        upgradNoNew = 0;
//        upgradSuccess  = 0;
//        upgradLanErr = 0;
//        upgradVerErr = 0;
//
//        connectNext();
    }

    public Handler getHandler() {
        return this.handler;
    }

    public void updateInfo() {

        //int temp = currConnectIndexMax - upgradSuccess - upgradVerErr - upgradLanErr;// - upgradNoNew;

        addLog(
                +(currConnectIndex + 1) + "/" + lstDevices.size()
                        + "   成功:" + upgradSuccess
                        + "   升级失败:" + (lstDevices.size() - upgradSuccess -  upgradVerErr - upgradLanErr)//upgradFailure
                        + "   版本错误:" + upgradVerErr
                        + "   语言错误:" + upgradLanErr);

        tvCount.setText((currConnectIndex + 1) + " / "+lstDevices.size()+"");
        tvSuccess.setText(upgradSuccess+"");
        tvFailure.setText((lstDevices.size() - upgradSuccess -  upgradVerErr - upgradLanErr)+"");
        tvLanErr.setText(upgradLanErr+"");
        tvVerErr.setText(upgradVerErr+"");



        if(currConnectIndex>currConnectIndexMax)
            currConnectIndexMax = currConnectIndex;
    }

    public void handleMsg(Message msg) {

        Bundle data = msg.getData();
        switch (msg.what) {
            case CommDefine.MESSAGE_CLIENT:
                switch (msg.arg1) {
                    case CommDefine.MESSAGE_CLIENT_ADD_LOG:
                        String tag = msg.getData().getString("TAG", "");
                        String text = msg.getData().getString("TEXT", "");
                        addLog(tag, text);
                        break;
                    case CommDefine.MESSAGE_CLIENT_SEARCH_FINISH:
//                        if(btAdapt.isDiscovering()) btAdapt.cancelDiscovery();

//                        btnSearch.setText("搜索设备");
//                        isSearch = false;
//                        if (isSearch) {
//                            addLog(TAG, "MESSAGE_CLIENT_SEARCH_FINISH");
//                            searchFinish();
//                        }

                        break;
                    case CommDefine.MESSAGE_CLIENT_PAIR_FINISH:
//                        if (isPair) {
//                            //addLog(TAG, "MESSAGE_CLIENT_PAIR_FINISH");
//                          pairFinish(true);
//                        }
                        break;
                    case CommDefine.MESSAGE_CLIENT_PAIR_CANCEL:
//                        if (isPair) {
//                            //addLog(TAG, "MESSAGE_CLIENT_PAIR_CANCEL");
//                            pairFinish(false);
//                        }
                        break;
                }
                break;
            case CommDefine.MESSAGE_SEARCH:
                switch (msg.arg1) {
                    case CommDefine.MESSAGE_SEARCH_FOUND:
//                        BluetoothDevice device = msg.getData().getParcelable(BluetoothDevice.EXTRA_DEVICE);
//                        String str = "未配对 | " + device.getAddress();
//                        if (MainActivity.lstDevicesText.indexOf(str) == -1) {// 防止重复添加
//                            if (isSendCmd(device.getAddress())) {
//                                str = str + " | 已发指令";
//                            }
//                            lstDevicesText.add(str); // 获取设备名称和mac地址
//                            lstDevices.add(device);
//                        }
//                        CommDefine.addLog(TAG, str);
//                        adtDevicesText.notifyDataSetChanged();
                        break;
                }
                break;
            case CommDefine.MESSAGE_UPGRAD:
                switch (msg.arg1) {
                    case CommDefine.MESSAGE_UPGRAD_CONNECT_FAIL:
                        upgradFailure++;
                        connectNext();
                        break;
                    case CommDefine.MESSAGE_UPGRAD_START:
                        mbtnUpgrad.setText("正在升级[" + lstDevices.get(currConnectIndex).getAddress() + "]-");
                        mbtnUpgrad.setMax(msg.arg2);
                        mbtnUpgrad.setProgress(0);
                        break;
                    case CommDefine.MESSAGE_UPGRAD_UPDATEING:
                        mbtnUpgrad.setProgress(msg.arg2);
                        break;
                    case CommDefine.MESSAGE_UPGRAD_SUCCESS:
                        mbtnUpgrad.setProgress(0);
                        CommDefine.addLog(TAG, "升级完成");

                        bh.stop();
                        int index = -1;
                        for (int j = 0; j < lstHistoricalDevice.size(); j++) {
                            if (lstHistoricalDevice.get(j).getAddress().equals(lstDevices.get(currConnectIndex).getAddress())) {
                                index = j;
                                break;
                            }
                        }
                        if (index == -1) {
                            Device device = new Device();
                            device.setAddress(lstDevices.get(currConnectIndex).getAddress());
                            device.setIs_send_cmd(true);
                            device.setSend_date(new Date());
                            device.saveThrows();

                            lstHistoricalDevice.add(device);
                        } else {
                            lstHistoricalDevice.get(index).setIs_send_cmd(true);
                            lstHistoricalDevice.get(index).setSend_date(new Date());
                            lstHistoricalDevice.get(index).saveThrows();
                        }


                        if(lstDevicesText.get(currConnectIndex).indexOf("已升级")>=0){

                        } else {
                            String temp = lstDevicesText.get(currConnectIndex) + " | 已升级";
                            lstDevicesText.set(currConnectIndex,temp);
                            adtDevicesText.notifyDataSetChanged();
                        }


//                        mbtnUpgrad.setText(iDelayCount + "秒后进入烤机模式...");
//                        CommDefine.addLog(TAG, iDelayCount + "秒后进入烤机模式...");
//                        handConnectNext.removeCallbacks(runConnectNext);
//                        iDelayIndex = 0;
//                        handConnectNext.postDelayed(runConnectNext, 1000);

                        // 将之前升级成功的设备进入考机模式
                        //if ((currConnectIndex - 1) >= 0)
                        //    currConnectIndex = currConnectIndex - 2;
                        currConnectIndex = -1;
                        upgradLanErr = 0;
                        upgradVerErr = 0;
                        upgradSuccess++;

                        updateInfo();
                        connectNext();
                        break;
                    case CommDefine.MESSAGE_UPGRAD_NO_NEW:
                        upgradNoNew++;
                        if(lstDevicesText.get(currConnectIndex).indexOf("烤机中")>=0){

                        } else {
                            String temp = lstDevicesText.get(currConnectIndex) + " | 烤机中";
                            lstDevicesText.set(currConnectIndex,temp);
                            adtDevicesText.notifyDataSetChanged();
                        }
                        connectNext();
                        break;
                    case CommDefine.MESSAGE_UPGRAD_FAILURE:
                        mbtnUpgrad.setProgress(mbtnUpgrad.getMax());
                        upgradFailure++;

                        updateInfo();
                        connectNext();
                        break;
                    case CommDefine.MESSAGE_UPGRAD_ERR_CMD:
                        //upgradFailure++;
                        connectNext();
                        break;
                    case CommDefine.MESSAGE_UPGRAD_ERR_VER:
                        upgradVerErr++;

                        updateInfo();
                        connectNext();
                        break;
                    case CommDefine.MESSAGE_UPGRAD_ERR_LAN:
                        upgradLanErr++;

                        updateInfo();
                        connectNext();
                        break;
                }
                break;
        }
    }


    @Subscribe
    public void onEventMainThread(CommEvent commEvent) {
        Message msg = commEvent.getMsg();
        handleMsg(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus

        BluetoothHandler.getInstance().stop();

    }

    public void updateCurrVerInfo(int name, int lan) {

        String title = "升级";
        switch (name) {
            case 0: //B341;
                switch (lan) {
                    case 0: //中文
                        currVerKey = "B341_zh_CN";
                        title = title + " [B341-中文";
                        break;
                    case 1: //英文
                        currVerKey = "B341_en";
                        title = title + " [B341-英文";
                        break;
                    case 2: //俄文
                        currVerKey = "B341_ru";
                        title = title + " [B341-俄文";
                        break;
                }
                break;
            case 1: //H501
                switch (lan) {
                    case 0: //中文
                        currVerKey = "H501_zh_CN";
                        title = title + " [H501-中文";
                        break;
                    case 1: //英文
                        currVerKey = "H501_en";
                        title = title + " [H501-英文";
                        break;
                    case 2: //俄文
                        currVerKey = "H501_ru";
                        title = title + " [H501-俄文";
                        break;
                }
                break;
        }

        currVerInfo = Upgrad.getInstance().getMaxVerInfo(currVerKey);
        if (currVerInfo == null) {
            Toast.makeText(MainActivity.this, "未发现对于版本的升级包!", Toast.LENGTH_LONG).show();
            return;
        }
        title = title + "-"+currVerInfo.maxBinVer+"]";
        Log.i(TAG, currVerKey);
        Log.i(TAG, "lanIndex = " + currVerInfo.lanId);
        Log.i(TAG, "maxMcuVer = " + currVerInfo.maxMcuVer + " = " + currVerInfo.maxMcuVerFile);
        Log.i(TAG, "maxBinVer = " + currVerInfo.maxBinVer + " = " + currVerInfo.maxBinVerFile);

        if (mUpgardFlag)
            title = title + "[强]";
        this.setTitle(title);

    }

    public void search() {
        if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
            Toast.makeText(context, "请先打开蓝牙", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        if (btAdapt.isDiscovering())
            btAdapt.cancelDiscovery();
        lstDevicesText.clear();
        addLog(Log.INFO, "开始搜索设备...");

//        isSearch = true;
//        btnClearPair.setEnabled(false);
//        mbtnUpgrad.setText("正在搜索设备...");

        Object[] lstDevice = btAdapt.getBondedDevices().toArray();
        for (int i = 0; i < lstDevice.length; i++) {
            BluetoothDevice device = (BluetoothDevice) lstDevice[i];

            if (device.getName().equals("V-checker")) {
                String str = "已配对 | " + device.getAddress();

                if (isSendCmd(device.getAddress())) {
                    str = str + " | 已发指令";
                }
                addLog(Log.INFO, str);
                lstDevicesText.add(str); // 获取设备名称和mac地址
                adtDevicesText.notifyDataSetChanged();

                lstDevices.add(device);
            }
        }
        //setTitle("本机蓝牙地址：" + btAdapt.getAddress());
        btAdapt.startDiscovery();
    }

    public boolean isSendCmd(String strAddress) {
        for (int i = 0; i < lstHistoricalDevice.size(); i++) {
            if (lstHistoricalDevice.get(i).getAddress().equals(strAddress)) {
                return true;
            }
        }
        return false;
    }

    public void searchFinish() {
        Toast.makeText(context, "搜索设备完成!", Toast.LENGTH_LONG).show();


        btnClearPair.setEnabled(true);
        isSearch = false;
        isPair = false;
        mbtnUpgrad.setText("正在配对设备...");
        btnClearPair.setText("配对设备");
        currPairIndex = -1;

        for (BluetoothDevice device : lstDevices) {
            if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                currPairIndex = 0;
                pair(device.getAddress(), "1234");
                break;
            }
        }
        if (currPairIndex < 0) {
            addLog(Log.INFO, "未发现需要配对的设备！");
            mbtnUpgrad.setText("搜索设备");
            mbtnUpgrad.setEnabled(true);
            spinName.setEnabled(true);
            spinLan.setEnabled(true);
            isSearch = isPair = isConnect = false;
        }
    }

    public void pairFinish(boolean result) {
        isPair = false;
        if (result) {
            String str = lstDevicesText.get(currPairIndex).replace("未配对", "已配对");
            lstDevicesText.set(currPairIndex, str);
            adtDevicesText.notifyDataSetChanged();

            addLog(Log.INFO, "配对完成！");

//            //配对下一个设备
//            while ((currPairIndex++) < (lstDevices.size() - 1)) {
//                Log.i(TAG, "currPairIndex = " + currPairIndex + " / " + lstDevices.size());
//                if (lstDevices.get(currPairIndex).getBondState() != BluetoothDevice.BOND_BONDED
//                        || currPairIndex < 5) {
//                    pair(lstDevices.get(currPairIndex).getAddress(), "1234");
//                    break;
//                }
//            }
//
//            if (currPairIndex == lstDevices.size()) {
//                addLog("全部配对完成");
//                currConnectIndex = 0;
//                isPair = false;
//                isConnect = true;
//                addLog("连接蓝牙:" + lstDevices.get(currConnectIndex).getAddress());
//                bh = new BluetoothHandler(context, handler);
//                bh.connect(lstDevices.get(currConnectIndex));
//
//            }

        } else {
//            //配对下一个设备
//            while ((currPairIndex++) < (lstDevices.size() - 1)) {
//                Log.i(TAG, "currPairIndex = " + currPairIndex + " / " + lstDevices.size());
//                if (lstDevices.get(currPairIndex).getBondState() != BluetoothDevice.BOND_BONDED
//                        || currPairIndex < 5) {
//                    pair(lstDevices.get(currPairIndex).getAddress(), "1234");
//                    break;
//                }
//            }
        }

    }

    public void connectNext() {
        //连接下一个设备
        while ((currConnectIndex++) < (lstDevices.size() - 1)) {
            Log.i(TAG, "currConnectIndex = " + currConnectIndex + " / " + lstDevices.size());
            if (lstDevices.get(currConnectIndex).getBondState() == BluetoothDevice.BOND_BONDED) {
                addLog("");
                addLog("连接蓝牙:" + lstDevices.get(currConnectIndex).getAddress());

                mbtnUpgrad.setText("正在连接[" + lstDevices.get(currConnectIndex).getAddress() + "]");
                if(lstDevicesText.get(currConnectIndex).indexOf("烤机中")>0){
                    addLog("正在烤机");
                } else {
                    bh = new BluetoothHandler(context, handler);

                    bh.connect(lstDevices.get(currConnectIndex), mUpgardFlag, isSendCmd(lstDevices.get(currConnectIndex).getAddress()));
                    break;
                }
            }
        }

        if (currConnectIndex == lstDevices.size()) {


//            //重复连接三次，处理连接失败的情况
//            if(upgradSuccess != (lstDevices.size()-upgradLanErr-upgradVerErr) && reconectCounter<3){
//                handReconnect.postDelayed(runReconnect,60*1000);
//            }

            if(reconectCounter == 0) {
                addLog("120秒后将最后一个升级设备进入烤机模式");
                //处理最后一个升级的设备进入烤机模式
                handReconnect.postDelayed(runReconnect, 120 * 1000);
                //mbtnUpgrad.setText("升级完成，进行最");
            } else{
                addLog("全部连接完成");
                mbtnUpgrad.setText("开始升级");
                mbtnUpgrad.setEnabled(true);
                spinName.setEnabled(true);
                spinLan.setEnabled(true);
                btnSearch.setEnabled(true);
                btnClearPair.setEnabled(true);
                isSearch = isPair = isConnect = false;

                String msg = "全部操作完成" + "\n\n"
                        + "搜索设备：" + lstDevices.size() + "\n"
                        + "成功升级：" + upgradSuccess + "\n"
                        + "版本错误：" + upgradVerErr + "\n"
                        + "语言错误：" + upgradLanErr + "\n";
                final VDialog dlgOk = DlgUtils.showOk(MainActivity.this, msg);
                dlgOk.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        switch (dlgOk.getResult()) {
                            case VDialog.RESULT_CANCEL:
                                //exitApp();
                                break;
                            case VDialog.RESULT_CONTINUE:

                                btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能
                                for (Object obj : btAdapt.getBondedDevices()) {
                                    BluetoothDevice bd = (BluetoothDevice) obj;
                                    unpair(bd);
                                }
                                btAdapt.disable();
                                if (!btAdapt.isEnabled())
                                    btAdapt.enable();   //打开蓝牙

                                startUpgrad();
                                break;
                        }
                    }
                });
                dlgOk.show();
            }
            //
        } else {

            updateInfo();
        }

    }

    public void exitApp(){

        System.exit(0);
    }

    int reconectCounter = 0;
    Handler handReconnect = new Handler();
    Runnable runReconnect = new Runnable() {
        @Override
        public void run() {
            handReconnect.removeCallbacks(runReconnect);
            reconectCounter++;
            currConnectIndex = -1;

            upgradLanErr = 0;
            upgradVerErr = 0;

            connectNext();
        }
    };

    public synchronized void addLog(String msg) {
        addLog(TAG, Log.INFO, msg);
    }

    public synchronized void addLog(String tag, String msg) {
        addLog(tag, Log.INFO, msg);
    }

    public synchronized void addLog(int type, String msg) {
        addLog(TAG, type, msg);
    }

    public synchronized void addLog(String tag, int type, String msg) {
        switch (type) {
            case Log.INFO:
                Log.i(TAG, msg);
                strLog.insert(0, msg + "\n");
                //strLog = msg + "\n" + strLog;
                break;
            case Log.DEBUG:
                Log.d(TAG, msg);
                break;
            default:
                Log.i(TAG, msg);
                break;
        }

    }

    Handler handLog = new Handler();
    Runnable runLog = new Runnable() {
        @Override
        public void run() {
            handLog.removeCallbacks(runLog);
            tvLog.setText(strLog);
            handLog.postDelayed(runLog, 1000);
        }
    };

    private void unpair(BluetoothDevice device) {
        try {
            Method method = device.getClass().getMethod("removeBond", (Class[]) null);
            method.invoke(device, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        switch (id) {
            case R.id.itemShowLog:
                isShowLog = !isShowLog;
                if (isShowLog) {
                    svLog.setVisibility(View.VISIBLE);
                    item.setTitle(getResources().getString(R.string.hide_log));
                } else {
                    svLog.setVisibility(View.GONE);
                    item.setTitle(getResources().getString(R.string.open_log));
                }
                break;
            case R.id.itemPauseLog:
                isPauseLog = !isPauseLog;
                if (isPauseLog) {
                    item.setTitle(getResources().getString(R.string.show_log));
                } else {
                    item.setTitle(getResources().getString(R.string.pause_log));
                }
                break;
            case R.id.itemClearLog:
                strLog.delete(0, strLog.length());
                tvLog.setText("");

//                for (int i = 0; i < lstDevices.size(); i++) {
//                    if (lstDevices.get(i).getBondState() == BluetoothDevice.BOND_BONDED) {
//                        BluetoothDevice device = lstDevices.get(i);
//                        try {
//                            ClsUtils.removeBond(device.getClass(), device);
//                        }catch (Exception ex){
//
//                        }
//                    }
//                }
                break;
            case R.id.itemClearDB:
                DataSupport.deleteAll(Device.class);
                break;
        }

        return super.onOptionsItemSelected(item);
    }


    public static BluetoothDevice remoteDevice = null;
    static Handler handAutoPair = new Handler();
    static Runnable runAutoPair = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            handAutoPair.removeCallbacks(runAutoPair);
//            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
//            ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
//            String packageName = cn.getPackageName();
            ShellUtils.CommandResult cr = ShellUtils.execCommand("input text '1234'", true);
            cr = ShellUtils.execCommand("input tap 561 1208", true);
        }
    };

    public boolean pair(String strAddr, String strPsw) {
        boolean result = false;
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();

        if (!BluetoothAdapter.checkBluetoothAddress(strAddr)) { // 检查蓝牙地址是否有效
            addLog(Log.INFO, "蓝牙设备无效!");
            return false;
        }

        BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr);

        mbtnUpgrad.setEnabled(false);
        btnClearPair.setText("正在配对设备...");
        isPair = true;

        try {
            addLog(Log.INFO, "开始配对：" + strAddr);

//            ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对
            ClsUtils.createBond(device.getClass(), device);

            handAutoPair.postDelayed(runAutoPair, 500);
            remoteDevice = device; // 配对完毕就把这个设备对象传给全局的remoteDevice
            result = true;
        } catch (Exception e) {
            // TODO Auto-generated catch block

            addLog(Log.INFO, "setPiN 失败!");
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 0: {

                final VDialog dlgConnect = DlgUtils.showConnect(MainActivity.this, true);
                dlgConnect.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        // TODO Auto-generated method stub
                        if (dlgConnect.getResult() == VDialog.RESULT_CONFIG) {
                            Intent intent = new Intent(
                                    Settings.ACTION_BLUETOOTH_SETTINGS);
                            startActivityForResult(intent, 0);
                        } else if (dlgConnect.getResult() == VDialog.RESULT_OK) {


                            if (btAdapt.isDiscovering()) btAdapt.cancelDiscovery();
                            isSearch = false;
                            btnSearch.setText("搜索设备");
                            lstDevices.clear();
                            lstDevicesText.clear();
                            Object[] lstDevice = btAdapt.getBondedDevices().toArray();

                            for (int i = 0; i < lstDevice.length; i++) {
                                BluetoothDevice device = (BluetoothDevice) lstDevice[i];

                                if (device.getName().equals("V-checker")) {
                                    lstDevices.add(device);

                                    if (isSendCmd(device.getAddress())) {
                                        lstDevicesText.add(device.getAddress() + " | 已升级");
                                    } else {
                                        lstDevicesText.add(device.getAddress());
                                    }
                                }
                            }
                            adtDevicesText.notifyDataSetChanged();

                            upgradFailure = 0;
                            upgradNoNew = 0;
                            upgradSuccess = 0;
                            upgradLanErr = 0;
                            upgradVerErr = 0;

                            reconectCounter = 0;
                            currConnectIndex = -1;
                            currConnectIndexMax = 0;
                            connectNext();
                        } else {
                            exitApp();
                        }
                    }
                });

                dlgConnect.show();
                break;
            }
        }
    }

    public static long mExitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if(System.currentTimeMillis()-mExitTime >2000){
                Toast.makeText(this,"再按一次退出软件",Toast.LENGTH_LONG).show();
                mExitTime = System.currentTimeMillis();
                return true;
            }
            exitApp();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
